//
//  YZMTrendView.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/12.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMTrendView.h"
#import "YZMQuoteStyle.h"
#import "YZMTrendPacket.h"
#import "NSString+Utils.h"
#import "YZMTrendItem.h"

//TODO: draw methods using 8 later

#define TOTALPOINTS 240

#define SCALESTEXTHEIGHT 16

@interface YZMTrendView ()
{
    NSInteger _currentIndex;
    CAGradientLayer *_gradientLayer;
}
@end

@implementation YZMTrendView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame: frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        _gradientLayer = [[CAGradientLayer alloc] init];
        [self.layer addSublayer:_gradientLayer];
        self.styleDict = [YZMQuoteStyle trendStyleDict];
        _currentIndex  = -1;
    }
    return self;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.backgroundColor = [UIColor clearColor];
    _gradientLayer = [[CAGradientLayer alloc] init];
    [self.layer addSublayer:_gradientLayer];
    self.styleDict = [YZMQuoteStyle trendStyleDict];
    _currentIndex  = -1;
}

#pragma mark - drawing

- (CGFloat)offsetOfIndex: (NSInteger)index inRect: (CGRect)rect
{
    CGFloat  separa = rect.size.width / TOTALPOINTS;
    if (index == 0) {
        return rect.origin.x + separa * index;
    }
    else
    {
        return rect.origin.x + separa * index+1;
    }
}

- (NSInteger)indexOfOffset: (CGFloat)offset inRect: (CGRect)rect
{
    if (offset < 0) {
        return 0;
    }
    CGFloat  separa = rect.size.width / TOTALPOINTS;
    NSInteger index = offset / separa;
    if (index >= self.dataArray.count) {
        return self.dataArray.count - 1;
    }
    else
    {
        return index;
    }
}


//分时
- (void)drawCurrentPriceLineInRect: (CGRect)rect inContext: (CGContextRef)context
{
    if (self.dataArray.count < 1) {
        return;
    }
    
    CGContextSaveGState(context);
    
    CGFloat pointValue = .0;
    
    CGFloat  baseY = rect.size.height / 2 + rect.origin.y;
    
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGMutablePathRef linePath = CGPathCreateMutable();
    CGFloat xOffset = rect.origin.x+1;
    CGFloat yOffset = 0;
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        YZMTrendPoint *obj = self.dataArray[i];
        pointValue = obj.price;
        
        xOffset  = [self offsetOfIndex:i inRect: rect];;
        yOffset = baseY + pointValue * rect.size.height /2;
        
        if (i == 0) {
            CGPathMoveToPoint(linePath, NULL, xOffset , yOffset);
        }
        else
        {
            CGPathAddLineToPoint(linePath, NULL , xOffset, yOffset);
        }
    }
    
    UIColor *tempColor = self.styleDict[TREND_CURRENT_LINE_COLOR_KEY];
    
    CGContextSetStrokeColorWithColor(context, tempColor.CGColor);
    CGContextAddPath(context, linePath);
    CGContextStrokePath(context);
    
    //fill path with content
    CGMutablePathRef fillPath = CGPathCreateMutableCopy(linePath);
    CGPathAddLineToPoint(fillPath, NULL, xOffset, rect.origin.y+rect.size.height);
    CGPathAddLineToPoint(fillPath, NULL, rect.origin.x, rect.origin.y+rect.size.height);
    CGPathCloseSubpath(fillPath);
    
    CGContextAddPath(context, fillPath);
    //CGContextClip(context);
    
    
    tempColor = self.styleDict[TREDN_FILL_COLOR_KEY];
    [tempColor setFill];
    CGContextFillPath(context);
    
    CGPathRelease(linePath);
    CGPathRelease(fillPath);
    
    CGContextRestoreGState(context);
}

//量竖线

- (void)drawLineSegmentsIn:(CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    
    CGFloat pointValue;
    
    CGFloat xOffset = 0;
    CGFloat yOffset = 0;
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        YZMTrendPoint *obj = self.dataArray[i];
        xOffset  = [self offsetOfIndex:i inRect: rect];;
        pointValue = obj.volume;
        
        yOffset = rect.origin.y + rect.size.height - pointValue*rect.size.height;
        CGContextMoveToPoint(context, xOffset, yOffset);
        CGContextAddLineToPoint(context, xOffset, rect.size.height+rect.origin.y);
        if (obj.rise) {
            UIColor *riseColor = self.styleDict[TREND_RISE_COLOR_KEY];
            if (riseColor == nil) {
                riseColor = [UIColor redColor];
            }
            
            CGContextSetStrokeColorWithColor(context, riseColor.CGColor);
        }
        else
        {
            UIColor *fallColor = self.styleDict[TREND_FALL_COLOR_KEY];
            if (fallColor == nil) {
                fallColor = [UIColor greenColor];
            }
            CGContextSetStrokeColorWithColor(context, fallColor.CGColor);
        }
        CGContextStrokePath(context);
    }
    
    CGContextRestoreGState(context);
}

//分时的框
- (void)drawPriceBoundsInRect:(CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    
    UIColor *borderColor = [self.styleDict objectForKey: CHAR_BOUND_COLOR_KEY];
    [borderColor setStroke];
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y+0.5);
    CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, rect.origin.y+0.5);
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y+rect.size.height-0.5);
    CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, rect.origin.y+rect.size.height-0.5);
    CGContextStrokePath(context);
    
    UIColor *lastCloseLineColor = [self.styleDict objectForKey: TREND_LASTCOLOSELINE_COLOR_KEY];
    [lastCloseLineColor setStroke];
    CGFloat dash[] = {4,4};
    CGContextSetLineDash(context, 0, dash, 2);
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y+rect.size.height/2);
    CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, rect.origin.y+rect.size.height/2);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

//量框
- (void)drawVolumeBoundsInRect:(CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    
    UIColor *borderColor = [self.styleDict objectForKey: CHAR_BOUND_COLOR_KEY];
    [borderColor setStroke];
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y+rect.size.height-0.5);
    CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, rect.origin.y+rect.size.height-0.5);
    CGContextStrokePath(context);
    
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

- (void)drawVerticalScales: (NSArray *)scales rightAlign: (BOOL)isRight inRect: (CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    NSInteger count = scales.count/2;
    CGFloat separa = rect.size.height / (count-1);
    CGFloat textHeight = SCALESTEXTHEIGHT;
    for (int i = 0; i < count; i++) {
        CGFloat moved = 0;
        if (i == 0) {
            moved = 2;
        }
        else if (i == count - 1)
        {
            moved = -SCALESTEXTHEIGHT - 2;
        }
        else
        {
            moved = - SCALESTEXTHEIGHT/2 - 6;
        }
        CGRect textRect = CGRectMake(rect.origin.x + (isRight ? -2 : 2), rect.origin.y + separa * i + moved, rect.size.width, textHeight);
        
        NSString *text = scales[i*2];
        UIColor *color = scales[i*2 + 1];
//        [color setFill];
//        [color setStroke];
        [text yz_drawInRect: textRect withFont: [UIFont systemFontOfSize: 10] lineBreakMode: NSLineBreakByClipping alignment: isRight?NSTextAlignmentRight : NSTextAlignmentLeft color:color];
        
    }
    CGContextRestoreGState(context);
}

//标度
- (void)drawScalesInRect: (CGRect)rect inContext: (CGContextRef)context
{
    NSString *topString = [NSString stringWithFormat: @"%.2f", self.basicPrice * (1+self.maxOffset)];
    NSString *midString = [NSString stringWithFormat: @"%.2f", self.basicPrice];
    NSString *bottomString = [NSString stringWithFormat: @"%.2f", self.basicPrice * (1-self.maxOffset)];
    UIColor *riseColor = self.styleDict[TREND_RISE_COLOR_KEY];
    UIColor *fallColor = self.styleDict[TREND_FALL_COLOR_KEY];
    UIColor *stableColor = self.styleDict[TREND_SCALES_COLOR];
    [self drawVerticalScales: @[topString, riseColor, midString, stableColor, bottomString, fallColor] rightAlign: NO inRect: rect inContext: context];
    
    NSString *maxOffsetStr = [NSString stringWithFormat: @"%.2f%%", self.maxOffset * 100.0];
    NSString *minOffsetStr = [NSString stringWithFormat: @"-%.2f%%", self.maxOffset * 100.0];
    [self drawVerticalScales: @[maxOffsetStr, riseColor, @"", stableColor, minOffsetStr, fallColor] rightAlign: YES inRect: rect inContext: context];
}

- (void)drawVolumeScalesinRect: (CGRect)rect inContext: (CGContextRef)context
{
    UIColor *stableColor = self.styleDict[CHAR_BOUND_COLOR_KEY];
    NSString *topString = [NSString stringWithFormat: @"%ld", (long)self.maxVolume/100];
    [self drawVerticalScales: @[topString, stableColor, @"", stableColor] rightAlign: NO inRect:rect inContext: context];
}

//时间
- (void)drawTimesInRect: (CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    
    UIColor *tempColor = self.styleDict[TREND_TIME_COLOR];
//    [tempColor setStroke];
//    [tempColor setFill];
    
    NSArray *timeStrs = @[@"9:30", @"11:30/13:00", @"15:00"];
    UIFont *font = [UIFont systemFontOfSize: 12];
    NSInteger strCount = timeStrs.count;
    for (NSInteger i = 0; i < strCount; i++) {
        NSString *str = timeStrs[i];
        CGFloat length = [str yz_sizeWithFont: font].width;
        CGPoint point = CGPointZero;
        point.y = rect.origin.y;
        if (i == 0) {
            point.x = rect.origin.x;
        }
        else if (i == strCount - 1)
        {
            point.x = rect.origin.x+rect.size.width-length-1;
        }
        else{
            CGFloat offset = 0;
            if (rect.size.width > 1) {
                offset = rect.size.width / (strCount-1);
            }
            point.x = rect.origin.x + offset *i - length/ 2;
        }
        [str yz_drawAtPoint: point withFont: font color:tempColor];
    }
    CGContextRestoreGState(context);
}


- (void)drawCurrentDataInRect: (CGRect)rect inContext: (CGContextRef)context
{
    CGContextSaveGState(context);
    
    CGFloat xOffset = [self offsetOfIndex: _currentIndex inRect:rect];
    CGRect backRect = CGRectMake(rect.origin.x, rect.origin.y, 80, 60);
    if (xOffset < rect.origin.x + rect.size.width / 2) {
        backRect = CGRectOffset(backRect, rect.size.width-backRect.size.width, 0);
    }
    
    UIColor *tempColor = self.styleDict[FOCUS_LINE_COLOR_KEY];
    [tempColor setStroke];
    CGContextStrokeRect(context, backRect);
    tempColor = self.styleDict[FOCUS_BACK_COLOR_KEY];
    [tempColor setFill];
    CGContextFillRect(context, backRect);
    NSString *currentPrice = [NSString stringWithFormat: @"价格:%.2f", self.currentItem.price];
    NSString *amount = [NSString stringWithFormat: @"量:%.0f", self.currentItem.amount/100];
    
    
    tempColor = self.styleDict[FOCUS_TEXT_COLOR_KEY];
    [tempColor setFill];
    NSArray *tempArray = @[currentPrice, amount];
    for (int i = 0; i < [tempArray count]; i++) {
        NSString *drawStr = tempArray[i];
        CGRect strRect = CGRectOffset(backRect, 2, i * 20);
        [drawStr yz_drawInRect: strRect withFont: [UIFont systemFontOfSize: 15] lineBreakMode: NSLineBreakByClipping];
    }
    
    tempColor = self.styleDict[FOCUS_LINE_COLOR_KEY];
    [tempColor setStroke];
    if (xOffset > backRect.origin.x && xOffset < backRect.origin.x + backRect.size.width) {
        CGContextMoveToPoint(context, xOffset, rect.origin.y + backRect.size.height);
    }
    else
    {
        CGContextMoveToPoint(context, xOffset, rect.origin.y);
    }
    
    CGContextAddLineToPoint(context, xOffset, rect.origin.y+rect.size.height);
    
    CGFloat yOffset = rect.origin.y + rect.size.height /2 + rect.size.height/2 * [self.dataArray[_currentIndex] price];
    if (yOffset > backRect.origin.y+backRect.size.height) {
        CGContextMoveToPoint(context, rect.origin.x, yOffset);
        CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, yOffset);
    }
    else if (xOffset < rect.origin.x + rect.size.width / 2) {
        CGContextMoveToPoint(context, rect.origin.x, yOffset);
        CGContextAddLineToPoint(context, backRect.origin.x, yOffset);
    }
    else
    {
        CGContextMoveToPoint(context, backRect.origin.x+backRect.size.width, yOffset);
        CGContextAddLineToPoint(context, rect.origin.x+rect.size.width, yOffset);
    }
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

- (void)drawCurrentAmountInRect: (CGRect)rect inContext: (CGContextRef)context
{
    CGFloat xOffset = [self offsetOfIndex: _currentIndex inRect:rect];
    CGContextMoveToPoint(context, xOffset, rect.origin.y);
    CGContextAddLineToPoint(context, xOffset, rect.origin.y+rect.size.height);
}


- (void)drawRect:(CGRect)rect
{
    [YZMAppStyle colorWithView:self withLayer:_gradientLayer withColorArray:@[(__bridge id)[UIColor colorWithRed: 115.0/255.0 green: 186/255.0 blue: 243/255.0 alpha: 0.1].CGColor, (__bridge id)[UIColor colorWithRed: 18/255.0 green: 28/255.0 blue: 37/255.0 alpha: 0.1].CGColor]];
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //边框设置
    CGFloat divideHeight = (rect.size.height - 25) * 2 / 3;
    CGFloat chartWidth = rect.size.width - 15;
    if (self.noLeftSpace) {
        chartWidth = rect.size.width;
    }
    CGRect priceRect = CGRectMake(15, 0, chartWidth, divideHeight);
    CGRect timeRect = CGRectMake(15, divideHeight, chartWidth, 20);
    CGRect amountRect = CGRectMake(15, divideHeight+20, chartWidth, divideHeight / 2);
    if (self.noLeftSpace) {
        priceRect.origin.x = 0;
        timeRect.origin.x = 0;
        amountRect.origin.x = 0;
    }
    
    //现价线
    [self drawCurrentPriceLineInRect: priceRect inContext: context];
    //时间
    [self drawTimesInRect: timeRect inContext: context];

    //量
    [self drawLineSegmentsIn: amountRect inContext: context];

    UIColor *boundsColor = self.styleDict[CHAR_BOUND_COLOR_KEY];
    [boundsColor setStroke];
    [self drawPriceBoundsInRect: priceRect inContext: context];
    [self drawVolumeBoundsInRect: amountRect inContext: context];

    [self drawScalesInRect: priceRect inContext: context];
    //[self drawVolumeScalesinRect: amountRect inContext: context];

    if (_currentIndex > -1) {
        [self drawCurrentDataInRect: priceRect inContext: context];
        [self drawCurrentAmountInRect: amountRect inContext: context];
    }
    
    
}

- (void)updateFromDataPacket: (YZMTrendPacket *)packet
{
    self.basicPrice = packet.closePrice;
    self.dataArray = [packet trendDrawPoints];
    self.maxOffset = packet.maxOffset;
    self.maxVolume = packet.maxVolume;
    
    [self setNeedsDisplay];
}

- (void)clearData
{
    self.basicPrice = 0;
    self.dataArray = nil;
    self.maxOffset = 0;
    self.maxVolume = 0;
    
    [self setNeedsDisplay];
}

@end
